(function(window){
var fireEvent = isTouch ? "touchend" : "click";

$(window).on("load", function(){
	$(".content .page, .content .subPage").each(function(node){
		node.iscroll = new iScroll(node);
		node.iscroll.moved = true;
	});
	
	var shortName = 'Kilo';
    var version = '1.0';
    var displayName = 'Kilo';
    var maxSize = 65536;
	db = openDatabase(shortName, version, displayName, maxSize);
    db.transaction(
        function(transaction) {
            transaction.executeSql(
                'CREATE TABLE IF NOT EXISTS entries ' +
                '  (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ' +
                '   date DATE NOT NULL, food TEXT NOT NULL, ' +
                '	calories INTEGER NOT NULL );'
            );
        }
    );
});

var mainTab = new $.Tab($(".content .page"),$(".menu li"), {selectWhen: fireEvent});

mainTab.afterSelect = function(i){
	i >= 0 && $("#back").css('display', '');
	try{
		i >= 0 && mainTab._contents[i].iscroll.refresh();
	}catch(e){ alert(e); }
}

$("#back").on(fireEvent, function(){
	var p = $(".subPage");
	if( p.hasClass("current") ){
		p.removeClass("current");
	} else {
		this.style.display = 'none';
		mainTab.select(-1);
	}
});

var flag;
$(".teachers > li").on(fireEvent, function(e){
	$("#loading").css("display", "block");
	
	setTimeout(function(){
		$(".subPage").addClass("current")[0].iscroll.refresh();
		$("#loading").css("display", "none");
	}, 500);
});

function findLi(node){
	while(node.nodeName != "LI"){
		if(node.nodeName == "BODY" || node.nodeName == "UL")	return;
		node = node.parentNode;
	}
	return node;
}

var touchedNode;
$(".teachers, .courses").on("touchstart", function(e){
	touchedNode = findLi(e.target);
	touchedNode && $(touchedNode).addClass("touched");
}).on("touchmove, touchend", function(e){
	touchedNode && $(touchedNode).removeClass("touched");
});

var tpl = '<# var i = 0; while(i++ < limit){ #>\
<div class="className">Text <#= i + 1 #>/<#= limit #></div>\
<# } #>\
';
console.log($.parseTpl(tpl, { limit: 5 }));

/*
function scrollRefresh(){
	try{
		$(".page.current")[0].scroll.refresh();
		$(".subPage.current")[0].scroll.refresh();
	}catch(e){
	}
}
 */

})(window);